package website

import (
	"net"
	"strings"

	"time"

	gossh "golang.org/x/crypto/ssh"
)

//Result *
type Result struct {
	Ok   bool        `json:"ok" xml:"ok"`
	Msg  string      `json:"msg" xml:"msg"`
	Data interface{} `json:"data" xml:"data"`
}

//User *
type User struct {
	User string `json:"user" xml:"user"`
	Pwd  string `json:"pwd" xml:"pwd"`
	Addr string `json:"addr" xml:"addr"`
}

//SSHVar *
type SSHVar struct {
	Name string `json:"name" xml:"name"`
	Val  string `json:"val" xml:"val"`
}

//WsParam *
type WsParam struct {
	Vars string `json:"vars" xml:"vars"`
	Cmd  string `json:"cmd" xml:"cmd"`
}

//RemoteSSH *
type RemoteSSH struct {
	User    string         `json:"user" xml:"user"`
	Pwd     string         `json:"pwd" xml:"pwd"`
	Addr    string         `json:"addr" xml:"addr"`
	Client  *gossh.Client  `json:"client" xml:"client"`
	Session *gossh.Session `json:"session" xml:"session"`
}

//NewSSH *
func NewSSH(user, pwd, addr string) (*RemoteSSH, error) {
	rAddr, err := net.ResolveTCPAddr("tcp4", addr)
	if nil != err {
		return nil, err
	}
	return &RemoteSSH{
		User: strings.TrimSpace(user),
		Pwd:  strings.TrimSpace(pwd),
		Addr: strings.TrimSpace(rAddr.String()),
	}, nil
}

//Connect *
func (r *RemoteSSH) Connect() (*RemoteSSH, error) {
	config := &gossh.ClientConfig{}
	config.SetDefaults()
	config.User = r.User
	config.Timeout = time.Second * 5
	config.Auth = []gossh.AuthMethod{gossh.Password(r.Pwd)}
	client, err := gossh.Dial("tcp", r.Addr, config)
	if nil != err {
		return nil, err
	}
	r.Client = client
	return r, nil
}
